<template>
  <div>
    <!-- 控制按钮 -->
    <div class="mb_8">
      <el-button size="medium" type="primary" icon="el-icon-circle-plus-outline" @click="addSubject()">新增科目</el-button>
      <el-button :loading="importLoading" size="medium" type="primary" @click="addSubjectFormTemplate()">导入模板</el-button>
    </div>
    <el-table v-loading="pageLoading" size="mini" :data="tableData" class="gl_table_noBorder" style="width: 100%">
      <el-table-column width="45">
        <template slot-scope="{ row }">
          <div v-if="row.isOfficial" class="flex_official">官</div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="科目名称">
        <template slot-scope="{ row }">
          <template v-if="row.isFromTemplate">
            <span>{{ row.name }}</span>
          </template>
          <template v-else>
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <el-input v-else v-model.trim="row.nameInput" style="width: 100%" size="mini" />
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="证书名称">
        <template slot-scope="{ row }">
          <template v-if="row.isFromTemplate">
            <span>{{ row.certificateName }}</span>
          </template>
          <template v-else>
            <span v-if="!row.isEdit">{{ row.certificateName }}</span>
            <el-input v-else v-model.trim="row.certificateNameInput" style="width: 100%" size="mini" />
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="证书类型">
        <template slot-scope="{ row }">
          <template v-if="row.isFromTemplate">
            <span>{{ row.certificateType }}</span>
          </template>
          <template v-else>
            <span v-if="!row.isEdit">{{ row.certificateType }}</span>
            <el-input v-else v-model.trim="row.certificateTypeInput" style="width: 100%" size="mini" />
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="证书等级">
        <template slot-scope="{ row }">
          <template v-if="row.isFromTemplate">
            <span>{{ row.certificateLevel }}</span>
          </template>
          <template v-else>
            <span v-if="!row.isEdit">{{ row.certificateLevel }}</span>
            <el-input v-else v-model.trim="row.certificateLevelInput" style="width: 100%" size="mini" />
          </template>
        </template>
      </el-table-column>
      <el-table-column width="200" label="会员价格">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">￥{{ formatMoney(row.memberPrice) }}</span>
          <el-input-number v-else v-model.trim="row.memberPriceInput" :min="0" :precision="2" :controls="false" type="number" size="mini" />
        </template>
      </el-table-column>
      <el-table-column width="200" label="非会员价格">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">￥{{ formatMoney(row.nonMemberPrice) }}</span>
          <el-input-number v-else v-model.trim="row.nonMemberPriceInput" :min="0" :precision="2" :controls="false" type="number" size="mini" />
        </template>
      </el-table-column>
      <el-table-column width="200" label="必报科目">
        <template slot-scope="{ row }">
          <template v-if="!row.isEdit">
            <span v-if="row.isEntryRequired">是</span>
            <span v-else>否</span>
          </template>
          <template v-else>
            <el-select v-model="row.isEntryRequiredInput" size="mini" placeholder="请选择科目是否必报">
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </template>
        </template>
      </el-table-column>
      <el-table-column width="180" label="操作">
        <template slot-scope="{ row, $index }">
          <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickEidt(row)">编辑</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickComplete(row)">完成</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickCancel(row)"><span class="gl_color_error">取消</span></el-button>
          <el-button v-if="!row.isEdit" :disabled="$index === 0" size="mini" type="text" @click="clickMoveUp(row)">上移</el-button>
          <el-button v-if="!row.isEdit" :disabled="$index === tableData.length - 1" size="mini" type="text" @click="clickMoveDown(row)">下移</el-button>
          <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickDel(row)"><span class="gl_color_error">删除</span></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增科目弹窗 -->
    <addDialog ref="refAddDialog" dialog-mode="Exam" @onSubmit="onSubmitAdd" />
    <!-- 导入模板弹窗 -->
    <importDialog ref="refImportDialog" dialog-mode="Exam" @onSubmit="onSubmitImport" />
  </div>
</template>

<script>
import addDialog from './subjectDialogAdd';
import importDialog from './subjectDialogImort';

import {
  api_POST_TrainSubject, // 创建科目
  api_PUT_TrainSubjectId, // 更新科目
  api_PUT_TrainSubjectIdSortOrder, // 更改顺序
  api_DELETE_TrainSubjectId, // 删除科目
  api_GET_TrainSubjectSubjectTemplates, // 获取科目模板
  api_POST_TrainSubjectSubjectByTemplate// 根据模板生成科目
} from '@/extend/api/trainswaggerApi/app.js';

export default {
  components: {
    addDialog,
    importDialog
  },
  props: {
    pageLoading: {
      type: Boolean,
      default: false
    },
    pageData: {
      type: Object,
      default () {
        return {};
      }
    },
    trainId: {
      type: String,
      require: true,
      default: ''
    }
  },
  data () {
    return {
      importLoading: false,
      tableData: []
    };
  },
  watch: {
    pageData: {
      deep: true,
      immediate: true,
      handler(val) {
        const _list = val.examSubjects || [];
        this.tableData = _list.map(item => {
          const _item = JSON.parse(JSON.stringify(item));
          _item.isEdit = false;
          _item.nameInput = '';
          _item.certificateLevelInput = '';
          _item.certificateTypeInput = '';
          _item.certificateNameInput = '';
          _item.memberPriceInput = '';
          _item.nonMemberPriceInput = '';
          _item.isEntryRequiredInput = '';
          return _item;
        });
      }
    }
  },
  methods: {
    addSubjectFormTemplate () {
      this.getSubjectTemplate();
    },
    // 获取科目模板
    getSubjectTemplate () {
      this.importLoading = true;
      api_GET_TrainSubjectSubjectTemplates({
        SubjectTypeCode: 'Exam',
        TrainnningId: this.trainId
      })
        .then(
          res => {
            this.importLoading = false;
            this.$refs.refImportDialog.openDialog({
              title: '科目模板',
              dto: res
            });
          }
        )
        .catch(
          error => {
            this.importLoading = false;
            this.$message({
              message: `科目模板获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    addSubject () {
      this.$refs.refAddDialog.openDialog();
    },
    onSubmitImport (vo) {
      const _vo = {
        trainningId: this.trainId,
        templateId: vo.templateId,
        isEntryRequired: vo.isEntryRequired,
        partIds: vo.radios.map(item => item.radios),
        memberPrice: this.yuanToFen(vo.memberPrice),
        nonMemberPrice: this.yuanToFen(vo.nonMemberPrice)
      };

      api_POST_TrainSubjectSubjectByTemplate(_vo)
        .then(
          res => {
            this.$message({
              message: `模板导入科目成功`,
              type: 'success',
              showClose: true
            });
            // this.$refs.refImportDialog.closeDialog();
            this.$refs.refImportDialog.changeLoading(false);
            this.$emit('getPageList');
          }
        )
        .catch(
          error => {
            this.$refs.refImportDialog.changeLoading(false);
            this.$message({
              message: `模板导入科目失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 编辑
    clickEidt (row) {
      console.log('row: ', row);
      const _memberPrice = this.formatMoney(row.memberPrice);
      const _nonMemberPrice = this.formatMoney(row.nonMemberPrice);
      row.memberPriceInput = Number(_memberPrice);
      row.nonMemberPriceInput = Number(_nonMemberPrice);
      row.nameInput = row.name;
      row.certificateTypeInput = row.certificateType;
      row.certificateLevelInput = row.certificateLevel;
      row.certificateNameInput = row.certificateName;
      row.isEntryRequiredInput = row.isEntryRequired;
      row.isEdit = true;
    },
    // 取消编辑
    clickCancel (row) {
      row.isEdit = false;
    },
    // 点击完成
    clickComplete (row) {
      row.isEdit = false;
      const _vo = {
        name: row.nameInput,
        certificateType: row.certificateTypeInput,
        certificateLevel: row.certificateLevelInput,
        certificateName: row.certificateNameInput,
        isEntryRequired: row.isEntryRequiredInput,
        memberPrice: this.yuanToFen(row.memberPriceInput),
        nonMemberPrice: this.yuanToFen(row.nonMemberPriceInput)
      };
      this.updateSubjectAPI(row.id, _vo);
    },
    // 编辑API
    updateSubjectAPI (id, vo) {
      this.$emit('changePageLoading', true);
      api_PUT_TrainSubjectId(id, vo)
        .then(
          res => {
            this.$emit('changePageLoading', false);
            this.$message({
              message: `编辑科目成功`,
              type: 'success',
              showClose: true
            });
            this.$emit('getPageList');
          }
        )
        .catch(
          error => {
            this.$emit('changePageLoading', false);
            this.$message({
              message: `编辑科目失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 确认提交新增科目
    onSubmitAdd (vo) {
      vo.subjectTypeCode = 'Exam';
      vo.trainningId = this.trainId;
      vo.memberPrice = this.yuanToFen(vo.memberPrice);
      vo.nonMemberPrice = this.yuanToFen(vo.nonMemberPrice);
      delete vo.subjectCertificateTypeCode;
      api_POST_TrainSubject(vo)
        .then(
          res => {
            this.$message({
              message: `新增科目成功`,
              type: 'success',
              showClose: true
            });
            this.$refs.refAddDialog.closeDialog();
            this.$emit('getPageList');
          }
        )
        .catch(
          error => {
            this.$message({
              message: `新增科目失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 上移
    clickMoveUp (row) {
      this.changeOrderAPI(row.id, {
        isUp: true
      });
    },
    // 下移
    clickMoveDown (row) {
      this.changeOrderAPI(row.id, {
        isUp: false
      });
    },
    // 改变科目顺序
    changeOrderAPI (id, vo) {
      this.$emit('changePageLoading', true);
      api_PUT_TrainSubjectIdSortOrder(id, vo)
        .then(
          res => {
            this.$message({
              message: `更改顺序成功`,
              type: 'success',
              showClose: true
            });
            this.$emit('getPageList');
          }
        )
        .catch(
          error => {
            this.$message({
              message: `更改顺序失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
            this.$emit('changePageLoading', false);
          }
        );
    },
    // 点击删除
    clickDel (row) {
      this.$confirm(`您确定删除${row.name}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            this.deleteAPI(row.id);
          }
        );
    },
    // 删除API
    deleteAPI (id) {
      this.$emit('changePageLoading', true);
      api_DELETE_TrainSubjectId(id)
        .then(
          res => {
            this.$message({
              message: `删除成功`,
              type: 'success',
              showClose: true
            });
            this.$emit('getPageList');
          }
        )
        .catch(
          error => {
            this.$emit('changePageLoading', false);
            this.$message({
              message: `删除失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 格式化货币格式 （分）
    formatMoney (num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 将元转化为分
    yuanToFen(moneyStr) {
      const _moneyStr = String(moneyStr);
      const yuan = Number(_moneyStr.split('.')[0]) || 0;
      const fen = Number(_moneyStr.split('.')[1]) || 0;
      return yuan * 100 + fen;
    }
  }
};
</script>

<style lang="scss" scoped>
  .mb_8 {
    margin-bottom: 8px;
  }
  .flex_official {
    box-sizing: border-box;
    width: 22px;
    height: 22px;
    font-size: 12px;
    line-height: 22px;
    text-align: center;
    color: #1990ff;
    border: 1px solid #1990ff;
    border-radius: 50%;
    background-color: #fff;
  }
</style>
